package com.sky.service.common.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.mapper.common.SetmealDishMapper;
import com.sky.mapper.common.SetmealMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.Setmeal;
import com.sky.pojo.SetmealDish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.SetmealService;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Override
    public Result<PageResult> page(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page = setmealMapper.page(setmealPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return Result.success(pageResult);
    }

    @Override
    public boolean add(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        int row = setmealMapper.add(setmeal);
        List<SetmealDish> setmealDish = setmealDTO.getSetmealDishes();
        if(setmealDTO.getSetmealDishes() != null&& !setmealDish.isEmpty()){
            setmealDish.forEach(dish -> dish.setSetmealId(setmeal.getId()));
            setmealDishMapper.addBatch(setmealDTO.getSetmealDishes());
        }
        return row>0 ;
    }

    @Override
    public SetmealVO findById(Long id) {
        SetmealVO setmealVO = setmealMapper.findById(id);
        return setmealVO;
    }

    @Override
    public boolean update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealDishMapper.deleteById(setmeal.getId());
        if(setmealDTO.getSetmealDishes() != null&& !setmealDTO.getSetmealDishes().isEmpty()){
            setmealDTO.getSetmealDishes().forEach(dish -> dish.setSetmealId(setmeal.getId()));
            setmealDishMapper.addBatch(setmealDTO.getSetmealDishes());
        }
        int row = setmealMapper.update(setmeal);
        return row>0;
    }

    @Override
    public boolean startOrStop(Integer status, Long id) {
        int row = setmealMapper.startOrStop(status, id);
        return row >0;
    }

    @Override
    public boolean delete(List<Long> ids) {
        int row = setmealMapper.deleteByIds(ids);
        return row >0;
    }
}
